const config = require("../config/redis");
var redis = require("redis");

var client = null;
function createClient(){
  client = redis.createClient(config.port, config.host, {auth_pass:config.password});

  client.on('connect', function () {
    //设置默认数据库
    client.select(config.dbNum);

    //60秒查询一次，模拟心跳，防止redis连接， 被无流量关闭
    setInterval(function(){
      client.get('ping', (err, rows) =>{
      });
    }, 60000);

  })
  client.on("error", function (err) {
    client.quit();
    console.log(err);
    //redis重连
    client = createClient();
  });
} 
createClient();


/**
 * 获取缓存
 * @param {Object} key
 */
function get(key, callback){
  client.get(key, (err, row)=>{
    if(typeof(row) == 'string'){
      row = JSON.parse(row);
    }
    callback(err, row);
  })
}

/**
 * 设置缓存
 * @param {Object} key
 * @param {Object} data
 * @param {Object} timeout
 */
function set(key, data, expire){
  data = JSON.stringify(data);
  //redis事务执行多条命令
  client.multi([
    ['set', key, data],
    ['expire', key, expire]
  ]).exec(function(err, rs){
    //console.log(err, rs);
  })
}


function flush(key){
  delete global.cacheData;
}

exports.get = get;
exports.set = set;
exports.flush = flush;